<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class login_model extends CI_Model {

    public function get_login_data($email = NULL, $encrypted_password = NULL) {
        if ($email != NULL AND $encrypted_password != NULL) {
            $sql = "select id from users where email like ? and encrypted_password like ?";
            $query = $this->db->query($sql, array($email, $encrypted_password));
            if ($query->num_rows() == 0) {
                $this->session->set_flashdata('not_found', 'Usuário ou Senha Inválidos!');
                redirect('login');
            }

            $id = $query->row()->id;

            $sql_nome = "select nome from user_infos where user_id like ?";
            $nome = $this->db->query($sql_nome, array($id))->row()->nome;

            $info = array('nome' => $nome, 'id' => $id, 'email' => $email);

            $sql_role = "select role_id from roles_users where user_id like ?";
            $role_user = $this->db->query($sql_role, array($id));
            if ($role_user->num_rows == 1) {
                $info['user_role'] = $role_user->row()->role_id;
            }else{
                $info['user_role'] = 0; //user_role = 0 se usuário padrão
            }
            return($info);
        }
    }

    public function altera_senha($id, $encrypted_password, $nova_encrypted_password) {
        if ($id != NULL AND $encrypted_password != NULL) {
            $sql = "select * from users where id like ? and encrypted_password like ?";
            $query = $this->db->query($sql, array($id, $encrypted_password));
            if ($query->num_rows() == 0) {
                $this->session->set_flashdata('senha_atual_erro', 'Senha Atual Não Confere!');
                redirect('login/alterar_senha');
            }
            $sql2 = "UPDATE selecaouab.users SET encrypted_password=? WHERE id=?;";
            $this->db->query($sql2, array($nova_encrypted_password, $id));

            $this->session->set_flashdata('alterar_senha_ok', 'Senha alterada com sucesso!');
            redirect('login/alterar_senha');
        }
    }

}
